package com.example.bishetianqi;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.bishetianqi.bean.WeatherBean;
import com.example.bishetianqi.db.DatabaseBean;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.List;

public class CityManagerAdapter extends BaseAdapter {

    Context context;
    List<DatabaseBean>databaseBeanList;

    public CityManagerAdapter(Context context, List<DatabaseBean> databaseBeanList) {
        this.context = context;
        this.databaseBeanList = databaseBeanList;
    }

    @Override
    public int getCount() {
        return databaseBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return databaseBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if (convertView==null) {
            convertView= LayoutInflater.from(context).inflate(R.layout.item_city_manager,null);
            holder=new ViewHolder(convertView);
            convertView.setTag(holder);
        }else {
            holder= (ViewHolder) convertView.getTag();
        }
        DatabaseBean bean=databaseBeanList.get(position);
        holder.cityTV.setText(bean.getCity());
        WeatherBean weatherBean = new Gson().fromJson(bean.getContent(), WeatherBean.class);
        WeatherBean.ResultsBean.WeatherDataBean weatherDataBean = weatherBean.getResults().get(0).getWeather_data().get(0);
        holder.conditionTV.setText("天气:"+weatherDataBean.getWeather());
        String[] strings=weatherDataBean.getDate().split("：");
        String todaytemp=strings[1].replace(")","");
        holder.tempTV.setText(todaytemp);
        holder.windTV.setText(weatherDataBean.getWind());
        holder.temprangeTV.setText(weatherDataBean.getTemperature());
        Picasso.with(context).load(weatherDataBean.getDayPictureUrl()).into(holder.weather_iconIV);
        return convertView;
    }

    class ViewHolder{
        TextView cityTV,tempTV,conditionTV,temprangeTV,windTV;
        ImageView weather_iconIV;
        public ViewHolder(View itemview){
            cityTV=itemview.findViewById(R.id.item_city_tv_city);
            conditionTV=itemview.findViewById(R.id.item_city_tv_condition);
            tempTV=itemview.findViewById(R.id.item_city_tv_temp);
            temprangeTV=itemview.findViewById(R.id.item_city_temprange);
            windTV=itemview.findViewById(R.id.item_city_wind);
            weather_iconIV=itemview.findViewById(R.id.item_city_iv_icon);
        }
    }
}
